class_name MovementComponent
extends Node2D

@export var base_speed := 150.0
@export var speed_scale := 1.5
@export var repel_scale := 5.0
@export var roll_speed := 350.0
@export var roll_cooldown := 1.0
@export var roll_duration := 0.2
@export var jump_force := 400.0
@export var gravity := 980.0

var player: CharacterBody2D
var is_dashing := false
var last_press_time := 0.0
var last_direction := 0.0
var can_roll := true
var is_rolling := false  # 新增互斥锁变量

@onready var animated_sprite := get_parent().get_node("PlayerAnimation")
@onready var player_state:StateComponent = get_parent().get_node("PlayerState")
@onready var player_sprite:CharacterBody2D = get_parent()

func _ready():
	EventBus.connect("player_jump", rebound)  # 新增事件监听
	EventBus.connect("player_hurt", hurt)  # 新增事件监听

#region 运动系统
func handle_movement(delta: float):
	handle_move(delta)
	handle_roll(delta)
	handle_jump()
	handle_fall(delta)

func handle_move(delta: float):
	var direction = Input.get_axis("move_left", "move_right")
	
	if PlayerEnums.AnimState.HURT == player_state.get_current_state():
		# 受伤时不允许移动
		return

	# 修改后的双击检测逻辑
	if Input.is_action_just_pressed("move_left") or Input.is_action_just_pressed("move_right"):
		var current_time = Time.get_ticks_msec()
		# 只允许同方向双击，且间隔小于300ms
		if current_time - last_press_time < 300 && direction == last_direction:
			is_dashing = true
		last_press_time = current_time
		last_direction = direction

	# 新增：当松开方向键时自动取消冲刺
	if direction == 0:
		is_dashing = false

	var speed = base_speed * speed_scale if is_dashing else base_speed
	# 新的速度计算（同步平台移动）
	var target_velocity = Vector2(
		direction * speed,
		player_sprite.velocity.y
	)

	# 使用物理插值避免抖动
	player_sprite.velocity = player_sprite.velocity.lerp(
		target_velocity,
		12 * delta if player_sprite.is_on_floor() else 4 * delta
	)
	# 新增：持续按住方向键时的冲刺保持逻辑
	if is_dashing && (Input.is_action_pressed("move_left") || Input.is_action_pressed("move_right")):
		player_sprite.velocity = player_sprite.velocity.lerp(
			target_velocity,
			12 * delta if player_sprite.is_on_floor() else 4 * delta
		)
	else:
		is_dashing = false

#region 翻滚系统
func handle_roll(delta: float):
	if Input.is_action_just_pressed("roll") and can_roll and player_sprite.is_on_floor() and not is_rolling:
		is_rolling = true
		player_state.transition_to(PlayerEnums.AnimState.ROLL)
		can_roll = false

		# 保存原始循环设置并禁用循环
		var original_loop = animated_sprite.sprite_frames.get_animation_loop("roll")
		animated_sprite.sprite_frames.set_animation_loop("roll", false)

		var roll_direction = -1 if animated_sprite.flip_h else 1
		player_sprite.velocity.x = roll_direction * roll_speed * delta

		animated_sprite.stop()
		animated_sprite.play("roll")

		# 等待动画完成
		await animated_sprite.animation_finished

		# 恢复原始循环设置
		animated_sprite.sprite_frames.set_animation_loop("roll", original_loop)

		var remaining_cooldown = max(roll_cooldown - roll_duration, 0.2)
		await get_tree().create_timer(remaining_cooldown).timeout

		player_state.transition_to(PlayerEnums.AnimState.IDLE)
		player_sprite.velocity.x = 0
		can_roll = true
		is_rolling = false

#region 跳跃系统
func handle_jump():
	# if Input.is_action_just_pressed("jump") and player_sprite.is_on_floor():
	# 	jump()
	if Input.is_action_just_pressed("jump"):
		jump()

#region 辅助功能
func handle_fall(delta):
	if not player_sprite.is_on_floor():
		# 应用重力前先同步平台垂直速度
		if player_sprite.is_on_wall() && player_sprite.get_wall_normal().y != 0:
			player_sprite.velocity.y = player_sprite.get_floor_velocity().y
		else:
			player_sprite.velocity.y += gravity * delta
		
		# 限制最大下落速度防止穿模
		player_sprite.velocity.y = min(player_sprite.velocity.y, 2000)

func jump():
	player_sprite.velocity.y = -jump_force

func rebound():
	if player_state.get_current_state() == PlayerEnums.AnimState.HURT:
		return
	jump()

func hurt(direction: int = -1):
	if direction < 0:
		player_sprite.position.x -= 10
		player_sprite.velocity.x = -base_speed * repel_scale
	else:
		player_sprite.position.x += 10
		player_sprite.velocity.x = base_speed * repel_scale
